<template>
  <div class="achievements-container">
    <div class="header">
      <h2>个人学术成果</h2>
      <el-button type="primary" @click="showAddDialog = true">新增学术成果</el-button>
    </div>

    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-value">{{ stats.total || 0 }}</div>
          <div class="stats-label">成果总量</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card approved">
          <div class="stats-value">{{ stats.approved || 0 }}</div>
          <div class="stats-label">已认证</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card pending">
          <div class="stats-value">{{ stats.pending || 0 }}</div>
          <div class="stats-label">评审中</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card rejected">
          <div class="stats-value">{{ stats.rejected || 0 }}</div>
          <div class="stats-label">待修订</div>
        </el-card>
      </el-col>
    </el-row>

    <el-card>
      <el-form :inline="true" class="filter-form">
        <el-form-item label="成果类型">
          <el-select v-model="filters.type" placeholder="全部类型" clearable>
            <el-option label="论文" value="论文" />
            <el-option label="纵向课题" value="纵向课题" />
            <el-option label="横向课题" value="横向课题" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="filters.status" placeholder="全部状态" clearable>
            <el-option label="评审中" value="待审核" />
            <el-option label="已认证" value="已通过" />
            <el-option label="待修订" value="已拒绝" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="filterAchievements">筛选</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="achievements" style="width: 100%">
        <el-table-column prop="title" label="成果标题" />
        <el-table-column prop="type" label="成果类型" width="120" />
        <el-table-column label="提交日期" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="审核状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="scope">
            <el-button link type="primary" @click="viewAchievement(scope.row)">查看</el-button>
            <el-button 
              link 
              type="primary" 
              :disabled="scope.row.status !== '待审核'" 
              @click="editAchievement(scope.row)">修改</el-button>
            <el-button 
              link 
              type="danger" 
              :disabled="scope.row.status !== '待审核'" 
              @click="deleteAchievement(scope.row)">撤回</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑成果对话框 -->
    <el-dialog 
      v-model="showAddDialog" 
      :title="isEdit ? '修改学术成果' : '新增学术成果'" 
      width="50%"
    >
      <el-form :model="achievementForm" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="成果标题" prop="title">
          <el-input v-model="achievementForm.title" placeholder="请输入学术成果标题" />
        </el-form-item>
        <el-form-item label="成果类型" prop="type">
          <el-select v-model="achievementForm.type" placeholder="请选择成果类型" @change="onTypeChange">
            <el-option label="论文" value="论文" />
            <el-option label="纵向课题" value="纵向课题" />
            <el-option label="横向课题" value="横向课题" />
          </el-select>
        </el-form-item>
        <!-- 论文字段 -->
        <template v-if="achievementForm.type === '论文'">
          <el-form-item label="期刊" prop="journal">
            <el-input v-model="achievementForm.journal" placeholder="请输入发表期刊名称" />
          </el-form-item>
          <el-form-item label="期号">
            <el-input v-model="achievementForm.issueNumber" placeholder="请输入期号" />
          </el-form-item>
          <el-form-item label="卷号">
            <el-input v-model="achievementForm.volumeNumber" placeholder="请输入卷号" />
          </el-form-item>
          <el-form-item label="页码">
            <el-input v-model="achievementForm.pageNumber" placeholder="请输入页码" />
          </el-form-item>
          <el-form-item label="检索级别">
            <el-select v-model="achievementForm.indexLevel" placeholder="请选择检索级别">
              <el-option label="SCI" value="SCI" />
              <el-option label="EI" value="EI" />
              <el-option label="ISTP" value="ISTP" />
              <el-option label="核心期刊" value="核心期刊" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="作者名单" prop="authors">
            <el-input v-model="achievementForm.authors" placeholder="请输入作者名单，多个作者用逗号分隔" />
          </el-form-item>
          <el-form-item label="第一作者">
            <el-input v-model="achievementForm.firstAuthor" placeholder="请输入第一作者姓名" />
          </el-form-item>
          <el-form-item label="通讯作者">
            <el-input v-model="achievementForm.correspondingAuthor" placeholder="请输入通讯作者姓名" />
          </el-form-item>
          <el-form-item label="发表日期">
            <el-date-picker
              v-model="achievementForm.publicationDate"
              type="date"
              placeholder="请选择发表日期"
              format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="影响因子">
            <el-input-number v-model="achievementForm.impactFactor" :min="0" :precision="3" placeholder="请输入影响因子" />
          </el-form-item>
          <el-form-item label="论文链接">
            <el-input v-model="achievementForm.paperLink" placeholder="请输入论文链接地址" />
          </el-form-item>
        </template>

        <!-- 纵向课题字段 -->
        <template v-if="achievementForm.type === '纵向课题'">
          <el-form-item label="项目号/批准号/合同号">
            <el-input v-model="achievementForm.projectNumber" placeholder="请输入项目号/批准号/合同号" />
          </el-form-item>
          <el-form-item label="项目编号">
            <el-input v-model="achievementForm.projectCode" placeholder="请输入项目编号" />
          </el-form-item>
          <el-form-item label="项目级别">
            <el-select v-model="achievementForm.projectLevel" placeholder="请选择项目级别">
              <el-option label="国家级" value="国家级" />
              <el-option label="省部级" value="省部级" />
              <el-option label="市厅级" value="市厅级" />
              <el-option label="校级" value="校级" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="总金额（万元）">
            <el-input-number v-model="achievementForm.totalAmount" :min="0" :precision="2" placeholder="请输入总金额" />
          </el-form-item>
          <el-form-item label="批准部门">
            <el-input v-model="achievementForm.approvalDepartment" placeholder="请输入批准部门" />
          </el-form-item>
          <el-form-item label="项目类型">
            <el-input v-model="achievementForm.projectType" placeholder="请输入项目类型" />
          </el-form-item>
          <el-form-item label="期限">
            <el-input v-model="achievementForm.duration" placeholder="请输入项目期限" />
          </el-form-item>
          <el-form-item label="到款记录">
            <el-input v-model="achievementForm.paymentRecord" type="textarea" rows="2" placeholder="请输入到款记录" />
          </el-form-item>
          <el-form-item label="参与人">
            <el-input v-model="achievementForm.participants" placeholder="请输入参与人，多人用逗号分隔" />
          </el-form-item>
          <el-form-item label="项目负责人">
            <el-input v-model="achievementForm.projectLeader" placeholder="请输入项目负责人" />
          </el-form-item>
          <el-form-item label="财务账号">
            <el-input v-model="achievementForm.financialAccount" placeholder="请输入财务账号" />
          </el-form-item>
          <el-form-item label="结题时间">
            <el-date-picker
              v-model="achievementForm.completionDate"
              type="date"
              placeholder="请选择结题时间"
              format="YYYY-MM-DD"
            />
          </el-form-item>
        </template>

        <!-- 横向课题字段 -->
        <template v-if="achievementForm.type === '横向课题'">
          <el-form-item label="合同号">
            <el-input v-model="achievementForm.contractNumber" placeholder="请输入合同号" />
          </el-form-item>
          <el-form-item label="合同总金额">
            <el-input-number v-model="achievementForm.contractAmount" :min="0" :precision="2" placeholder="请输入合同总金额" />
          </el-form-item>
          <el-form-item label="甲方单位名称">
            <el-input v-model="achievementForm.clientName" placeholder="请输入甲方单位名称" />
          </el-form-item>
          <el-form-item label="项目负责人">
            <el-input v-model="achievementForm.projectLeader" placeholder="请输入项目负责人" />
          </el-form-item>
          <el-form-item label="执行负责人">
            <el-input v-model="achievementForm.executiveLeader" placeholder="请输入执行负责人" />
          </el-form-item>
          <el-form-item label="期限">
            <el-input v-model="achievementForm.duration" placeholder="请输入项目期限" />
          </el-form-item>
          <el-form-item label="到款记录">
            <el-input v-model="achievementForm.paymentRecord" type="textarea" rows="2" placeholder="请输入到款记录" />
          </el-form-item>
          <el-form-item label="参与人">
            <el-input v-model="achievementForm.participants" placeholder="请输入参与人，多人用逗号分隔" />
          </el-form-item>
          <el-form-item label="财务账号">
            <el-input v-model="achievementForm.financialAccount" placeholder="请输入财务账号" />
          </el-form-item>
          <el-form-item label="结题时间">
            <el-date-picker
              v-model="achievementForm.completionDate"
              type="date"
              placeholder="请选择结题时间"
              format="YYYY-MM-DD"
            />
          </el-form-item>
        </template>
        <el-form-item label="上传证明材料">
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">支持 PDF、DOC、DOCX 等文档格式，单文件大小不超过 10MB</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAddEdit">取消</el-button>
          <el-button type="primary" @click="submitAchievement" :loading="submitting">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看成果对话框 -->
    <el-dialog v-model="showViewDialog" title="学术成果详情" width="50%">
      <div class="achievement-detail" v-if="currentAchievement">
        <div class="detail-item">
          <span class="label">成果标题：</span>
          <span class="value">{{ currentAchievement.title }}</span>
        </div>
        <div class="detail-item">
          <span class="label">成果类型：</span>
          <span class="value">{{ currentAchievement.type }}</span>
        </div>
        <div class="detail-item">
          <span class="label">作者/参与者：</span>
          <span class="value">{{ currentAchievement.authors || '无' }}</span>
        </div>
        <div class="detail-item" v-if="currentAchievement.journal">
          <span class="label">期刊/会议名称：</span>
          <span class="value">{{ currentAchievement.journal }}</span>
        </div>
        <div class="detail-item" v-if="currentAchievement.patentNo">
          <span class="label">专利号/授权号：</span>
          <span class="value">{{ currentAchievement.patentNo }}</span>
        </div>
        <div class="detail-item" v-if="currentAchievement.projectNo">
          <span class="label">项目编号：</span>
          <span class="value">{{ currentAchievement.projectNo }}</span>
        </div>
        <div class="detail-item" v-if="currentAchievement.publishDate">
          <span class="label">发表/获批日期：</span>
          <span class="value">{{ formatDate(currentAchievement.publishDate) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">提交日期：</span>
          <span class="value">{{ formatDate(currentAchievement.createdAt) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">审核状态：</span>
          <span class="value">
            <el-tag :type="getStatusType(currentAchievement.status)">{{ currentAchievement.status }}</el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="label">成果概述：</span>
          <p class="value description">{{ currentAchievement.description }}</p>
        </div>
        <div class="detail-item" v-if="currentAchievement.comments">
          <span class="label">评审意见：</span>
          <p class="value feedback">{{ currentAchievement.comments }}</p>
        </div>
        <div class="detail-item" v-if="currentAchievement.attachmentUrl">
          <span class="label">证明材料：</span>
          <div class="value">
            <el-button type="primary" link @click="downloadAttachment(currentAchievement.attachmentUrl)">下载材料</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted } from 'vue'
import type { FormInstance, UploadFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import StudentService from '@/api/student'

interface Achievement {
  id: number
  title: string
  type: string
  description: string
  authors?: string
  journal?: string
  patentNo?: string
  projectNo?: string
  publishDate?: string
  status: string
  attachmentUrl?: string
  createdAt: string
  updatedAt?: string
  comments?: string
}

export default defineComponent({
  name: 'StudentAchievements',
  setup() {
    const loading = ref(true)
    const submitting = ref(false)
    const achievements = ref<Achievement[]>([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const showAddDialog = ref(false)
    const showViewDialog = ref(false)
    const isEdit = ref(false)
    const currentAchievement = ref<Achievement | null>(null)
    const formRef = ref<FormInstance>()
    const fileList = ref<UploadFile[]>([])
    const stats = ref<Record<string, number>>({})

    const filters = reactive({
      type: '',
      status: ''
    })

    const achievementForm = reactive({
      id: 0,
      title: '',
      type: '',
      // 论文字段
      journal: '',
      issueNumber: '',
      volumeNumber: '',
      pageNumber: '',
      indexLevel: '',
      authors: '',
      firstAuthor: '',
      correspondingAuthor: '',
      publicationDate: '',
      impactFactor: null,
      paperLink: '',
      // 纵向课题字段
      projectNumber: '',
      projectCode: '',
      projectLevel: '',
      totalAmount: null,
      approvalDepartment: '',
      projectType: '',
      duration: '',
      paymentRecord: '',
      participants: '',
      projectLeader: '',
      financialAccount: '',
      completionDate: '',
      // 横向课题字段
      contractNumber: '',
      contractAmount: null,
      clientName: '',
      executiveLeader: '',
      // 通用字段
      attachmentUrl: ''
    })

    const rules = {
      title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
      type: [{ required: true, message: '请选择类型', trigger: 'change' }],
      description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
      authors: [{ required: true, message: '请输入作者', trigger: 'blur' }]
    }

    const getStatusType = (status: string) => {
      switch (status) {
        case '待审核':
          return 'info'
        case '已通过':
          return 'success'
        case '已拒绝':
          return 'danger'
        default:
          return ''
      }
    }

    const formatDate = (dateString: string) => {
      if (!dateString) return ''
      
      // 转换ISO格式日期为更友好的格式
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const fetchAchievements = async () => {
      loading.value = true
      try {
        const params: Record<string, string> = {}
        if (filters.type) params.type = filters.type
        if (filters.status) params.status = filters.status
        
        const response = await StudentService.getMyAchievements(params)
        achievements.value = response.data
        total.value = response.data.length
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '获取成果列表失败')
      } finally {
        loading.value = false
      }
    }

    const fetchStats = async () => {
      try {
        const response = await StudentService.getAchievementStats()
        stats.value = response.data
      } catch (error: any) {
        console.error('获取统计信息失败', error)
      }
    }

    const filterAchievements = () => {
      fetchAchievements()
    }

    const resetFilters = () => {
      filters.type = ''
      filters.status = ''
      fetchAchievements()
    }

    const handleSizeChange = (val: number) => {
      pageSize.value = val
    }

    const handleCurrentChange = (val: number) => {
      currentPage.value = val
    }

    const viewAchievement = async (achievement: Achievement) => {
      try {
        const response = await StudentService.getAchievementById(achievement.type, achievement.id)
        currentAchievement.value = response.data
        showViewDialog.value = true
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '获取成果详情失败')
      }
    }

    const editAchievement = async (achievement: Achievement) => {
      try {
        const response = await StudentService.getAchievementById(achievement.type, achievement.id)
        const data = response.data
        
        isEdit.value = true
        achievementForm.id = data.id
        achievementForm.title = data.title
        achievementForm.type = data.type
        
        // 根据类型设置对应字段
        if (data.type === '论文') {
          achievementForm.journal = data.journal || ''
          achievementForm.issueNumber = data.issueNumber || ''
          achievementForm.volumeNumber = data.volumeNumber || ''
          achievementForm.pageNumber = data.pageNumber || ''
          achievementForm.indexLevel = data.indexLevel || ''
          achievementForm.authors = data.authors || ''
          achievementForm.firstAuthor = data.firstAuthor || ''
          achievementForm.correspondingAuthor = data.correspondingAuthor || ''
          achievementForm.publicationDate = data.publicationDate || ''
          achievementForm.impactFactor = data.impactFactor || null
          achievementForm.paperLink = data.paperLink || ''
        } else if (data.type === '纵向课题') {
          achievementForm.projectNumber = data.projectNumber || ''
          achievementForm.projectCode = data.projectCode || ''
          achievementForm.projectLevel = data.projectLevel || ''
          achievementForm.totalAmount = data.totalAmount || null
          achievementForm.approvalDepartment = data.approvalDepartment || ''
          achievementForm.projectType = data.projectType || ''
          achievementForm.duration = data.duration || ''
          achievementForm.paymentRecord = data.paymentRecord || ''
          achievementForm.participants = data.participants || ''
          achievementForm.projectLeader = data.projectLeader || ''
          achievementForm.financialAccount = data.financialAccount || ''
          achievementForm.completionDate = data.completionDate || ''
        } else if (data.type === '横向课题') {
          achievementForm.contractNumber = data.contractNumber || ''
          achievementForm.contractAmount = data.contractAmount || null
          achievementForm.clientName = data.clientName || ''
          achievementForm.projectLeader = data.projectLeader || ''
          achievementForm.executiveLeader = data.executiveLeader || ''
          achievementForm.duration = data.duration || ''
          achievementForm.paymentRecord = data.paymentRecord || ''
          achievementForm.participants = data.participants || ''
          achievementForm.financialAccount = data.financialAccount || ''
          achievementForm.completionDate = data.completionDate || ''
        }
        
        achievementForm.attachmentUrl = data.attachmentUrl || ''
        
        showAddDialog.value = true
      } catch (error: any) {
        ElMessage.error(error.response?.data?.message || '获取成果详情失败')
      }
    }

    const deleteAchievement = (achievement: Achievement) => {
      ElMessageBox.confirm(
        '确定要删除这条成果记录吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await StudentService.deleteAchievement(achievement.type, achievement.id)
          ElMessage.success('删除成功')
          fetchAchievements()
          fetchStats()
        } catch (error: any) {
          ElMessage.error(error.response?.data?.message || '删除失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }

    const handleFileChange = (file: UploadFile) => {
      fileList.value = [file]
      // 在实际项目中，这里会上传文件并获取URL
      // 暂时模拟一个URL
      achievementForm.attachmentUrl = URL.createObjectURL(file.raw as Blob)
    }

    const onTypeChange = () => {
      // 清空所有字段，只保留标题和类型
      const currentTitle = achievementForm.title
      const currentType = achievementForm.type
      const currentId = achievementForm.id
      
      // 手动清空每个字段
      // 论文字段
      achievementForm.journal = ''
      achievementForm.issueNumber = ''
      achievementForm.volumeNumber = ''
      achievementForm.pageNumber = ''
      achievementForm.indexLevel = ''
      achievementForm.authors = ''
      achievementForm.firstAuthor = ''
      achievementForm.correspondingAuthor = ''
      achievementForm.publicationDate = ''
      achievementForm.impactFactor = null
      achievementForm.paperLink = ''
      // 纵向课题字段
      achievementForm.projectNumber = ''
      achievementForm.projectCode = ''
      achievementForm.projectLevel = ''
      achievementForm.totalAmount = null
      achievementForm.approvalDepartment = ''
      achievementForm.projectType = ''
      achievementForm.duration = ''
      achievementForm.paymentRecord = ''
      achievementForm.participants = ''
      achievementForm.projectLeader = ''
      achievementForm.financialAccount = ''
      achievementForm.completionDate = ''
      // 横向课题字段
      achievementForm.contractNumber = ''
      achievementForm.contractAmount = null
      achievementForm.clientName = ''
      achievementForm.executiveLeader = ''
      // 通用字段
      achievementForm.attachmentUrl = ''
      
      achievementForm.title = currentTitle
      achievementForm.type = currentType
      achievementForm.id = currentId
    }

    const resetForm = () => {
      achievementForm.id = 0
      achievementForm.title = ''
      achievementForm.type = ''
      // 论文字段
      achievementForm.journal = ''
      achievementForm.issueNumber = ''
      achievementForm.volumeNumber = ''
      achievementForm.pageNumber = ''
      achievementForm.indexLevel = ''
      achievementForm.authors = ''
      achievementForm.firstAuthor = ''
      achievementForm.correspondingAuthor = ''
      achievementForm.publicationDate = ''
      achievementForm.impactFactor = null
      achievementForm.paperLink = ''
      // 纵向课题字段
      achievementForm.projectNumber = ''
      achievementForm.projectCode = ''
      achievementForm.projectLevel = ''
      achievementForm.totalAmount = null
      achievementForm.approvalDepartment = ''
      achievementForm.projectType = ''
      achievementForm.duration = ''
      achievementForm.paymentRecord = ''
      achievementForm.participants = ''
      achievementForm.projectLeader = ''
      achievementForm.financialAccount = ''
      achievementForm.completionDate = ''
      // 横向课题字段
      achievementForm.contractNumber = ''
      achievementForm.contractAmount = null
      achievementForm.clientName = ''
      achievementForm.executiveLeader = ''
      // 通用字段
      achievementForm.attachmentUrl = ''
      fileList.value = []
      isEdit.value = false
    }

    const cancelAddEdit = () => {
      showAddDialog.value = false
      resetForm()
    }

    const submitAchievement = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            const data = {
              title: achievementForm.title,
              type: achievementForm.type,
              attachmentUrl: achievementForm.attachmentUrl,
              // 根据类型添加对应字段
              ...(achievementForm.type === '论文' && {
                journal: achievementForm.journal,
                issueNumber: achievementForm.issueNumber,
                volumeNumber: achievementForm.volumeNumber,
                pageNumber: achievementForm.pageNumber,
                indexLevel: achievementForm.indexLevel,
                authors: achievementForm.authors,
                firstAuthor: achievementForm.firstAuthor,
                correspondingAuthor: achievementForm.correspondingAuthor,
                publicationDate: achievementForm.publicationDate,
                impactFactor: achievementForm.impactFactor,
                paperLink: achievementForm.paperLink
              }),
              ...(achievementForm.type === '纵向课题' && {
                projectName: achievementForm.title, // 使用title作为项目名称
                projectNumber: achievementForm.projectNumber,
                projectCode: achievementForm.projectCode,
                projectLevel: achievementForm.projectLevel,
                totalAmount: achievementForm.totalAmount,
                approvalDepartment: achievementForm.approvalDepartment,
                projectType: achievementForm.projectType,
                duration: achievementForm.duration,
                paymentRecord: achievementForm.paymentRecord,
                participants: achievementForm.participants,
                projectLeader: achievementForm.projectLeader,
                financialAccount: achievementForm.financialAccount,
                completionDate: achievementForm.completionDate
              }),
              ...(achievementForm.type === '横向课题' && {
                projectName: achievementForm.title, // 使用title作为项目名称
                contractNumber: achievementForm.contractNumber,
                contractAmount: achievementForm.contractAmount,
                clientName: achievementForm.clientName,
                projectLeader: achievementForm.projectLeader,
                executiveLeader: achievementForm.executiveLeader,
                duration: achievementForm.duration,
                paymentRecord: achievementForm.paymentRecord,
                participants: achievementForm.participants,
                financialAccount: achievementForm.financialAccount,
                completionDate: achievementForm.completionDate
              })
            }
            
            if (isEdit.value) {
              await StudentService.updateAchievement(achievementForm.type, achievementForm.id, data)
              ElMessage.success('编辑成功')
            } else {
              await StudentService.createAchievement(data)
              ElMessage.success('提交成功，等待审核')
            }
            
            showAddDialog.value = false
            resetForm()
            fetchAchievements()
            fetchStats()
          } catch (error: any) {
            ElMessage.error(error.response?.data?.message || (isEdit.value ? '编辑失败' : '提交失败'))
          } finally {
            submitting.value = false
          }
        }
      })
    }

    const downloadAttachment = (url: string) => {
      // 在实际项目中，这里会下载附件
      window.open(url, '_blank')
    }

    onMounted(() => {
      fetchAchievements()
      fetchStats()
    })

    return {
      loading,
      submitting,
      achievements,
      total,
      currentPage,
      pageSize,
      filters,
      showAddDialog,
      showViewDialog,
      isEdit,
      currentAchievement,
      achievementForm,
      formRef,
      fileList,
      rules,
      stats,
      getStatusType,
      formatDate,
      filterAchievements,
      resetFilters,
      handleSizeChange,
      handleCurrentChange,
      viewAchievement,
      editAchievement,
      deleteAchievement,
      handleFileChange,
      onTypeChange,
      submitAchievement,
      downloadAttachment,
      cancelAddEdit
    }
  }
})
</script>

<style scoped>
.achievements-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
  padding: 15px;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stats-label {
  color: #909399;
  font-size: 14px;
}

.stats-card.approved .stats-value {
  color: #67c23a;
}

.stats-card.pending .stats-value {
  color: #e6a23c;
}

.stats-card.rejected .stats-value {
  color: #f56c6c;
}

.filter-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.achievement-detail {
  padding: 10px;
}

.detail-item {
  margin-bottom: 15px;
}

.label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
}

.description, .feedback {
  white-space: pre-line;
  line-height: 1.6;
  margin-top: 5px;
  color: #606266;
}

.feedback {
  color: #67c23a;
}
</style> 